package com.kh.samr.utils;

import lombok.SneakyThrows;

import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 枚举工具类
 *
 * @author Harry
 * @date 2020/12/17
 */
@SuppressWarnings("ALL")
public class EnumUtils {
	
	@SneakyThrows
	public static <E extends Enum<E>> Map<Integer, String> getAllMap(Class<E> enumClass) {
		Map<Integer, String> map = new LinkedHashMap();
		E[] es = enumClass.getEnumConstants();
		for (E e : es) {
			Method[] methods = e.getClass().getMethods();
			Method getCode = null;
			Method getValue = null;
			for (int i = 0, len = methods.length; i < len; i++) {
				if (methods[i].getName().equalsIgnoreCase("getCode")) {
					getCode = methods[i];
				}
				if (methods[i].getName().equalsIgnoreCase("getValue")) {
					getValue = methods[i];
				}
			}
			Object code = getCode.invoke(e, null);
			Object value = getValue.invoke(e, null);
			map.put(Integer.parseInt(code.toString()), value.toString());
		}
		return map;
	}
	
	@SneakyThrows
	public static <E extends Enum<E>> Map<Integer, String> getMapByCode(Class<E> enumClass, int code) {
		Map<Integer, String> map = new LinkedHashMap();
		E[] es = enumClass.getEnumConstants();
		for (E e : es) {
			Method[] methods = e.getClass().getMethods();
			Method getCode = null;
			Method getValue = null;
			for (int i = 0, len = methods.length; i < len; i++) {
				if (methods[i].getName().equalsIgnoreCase("getCode")) {
					getCode = methods[i];
				}
				if (methods[i].getName().equalsIgnoreCase("getValue")) {
					getValue = methods[i];
				}
			}
			int codeInt = Integer.parseInt(getCode.invoke(e, null).toString());
			if (codeInt == code) {
				map.put(code, getValue.invoke(e, null).toString());
				break;
			}
		}
		return map;
	}
	
}
